<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="btnFn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="delBtn(index)">删除</button>
            <button @click="editBtn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      uname: '',
      age: 0,
      gender: '',
      list: [],
      flog: true,
      index: null,
    }
  },
  methods: {
    btnFn() {
      if (this.uname.trim() === '' || this.age <= 0 || this.gender === '')
        return alert('请输入合理的数据')
      const data = {
        uname: this.uname,
        age: this.age,
        gender: this.gender,
      }
      if (this.flog) {
        this.list.push(data)
      } else {
        this.list.splice(this.index, 1, data)
      }
      this.uname = ''
      this.age = 0
      this.gender = ''
    },
    editBtn(index) {
      this.uname = this.list[index].uname
      this.age = this.list[index].age
      this.gender = this.list[index].gender
      this.flog = false
      this.index = index
    },
    delBtn(index) {
      this.list.splice(index, 1)
    },
  },
}
</script>
